package com.nulldev.util.locale;

import java.util.HashMap;
import java.util.LinkedList;

public class LocaleManager {

	public static final String VALUE_UNKNOWN = "val.unknown";
	private nLocale defaultLocale;
	private final LinkedList<nLocale> locales = new LinkedList<nLocale>();
	
	// value, data
	public static class nLocale {
		private final HashMap<String, String> data = new HashMap<String, String>();
		
		private final String name;
		public nLocale(final String locale) {
			this.name = locale;
		}
		
		public String getName() {
			return this.name;
		}
		
		public String registerValue(final String key, final String value) {
			return this.data.put(key, value);
		}
		
		public String getValue(final String key) {
			try {
				return (this.data.get(key) != null ? this.data.get(key) : key);
			}catch (Exception e) {
			}
			return key;
		}
		
		public HashMap<String, String> getInstance() {
			return (HashMap<String, String>) this.data.clone();
		}
	}
	
	public String get(final String string) {
		try {
			return this.defaultLocale.getValue(string);
		}catch (Exception e) {
			return string;
		}
	}
	
	public String get(final String string, final String locale) {
		for (final nLocale local : (LinkedList<nLocale>) this.locales.clone()) {
			if (local.getName().equals(locale)) {
				return local.getValue(string);
			}
		}
		try {
			return this.defaultLocale.getValue(string);
		}catch (Exception e) {
			return string;
		}
	}
	
	public String getFLB(final String string, final String locale, final String fallBackLocale) {
		for (final nLocale local : (LinkedList<nLocale>) this.locales.clone()) {
			if (local.getName().equals(locale)) {
				return local.getValue(string);
			}else if (local.getName().equals(fallBackLocale)) {
				return local.getValue(string);
			}
		}
		return string;
	}
	
	public boolean registerLocale(final nLocale locale) {
		return this.registerLocale(locale, false);
	}
	
	public boolean registerLocale(final nLocale locale, final boolean defaultLocale) {
		if (defaultLocale) {
			this.defaultLocale = locale;
		}
		return this.locales.add(locale);
	}
}
